package com.fq.core.service.impl;

import com.fq.client.domain.UserDO;
import com.fq.client.service.MessageService;
import com.fq.core.cache.RedisDAO;
import com.fq.core.dao.UserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author jifang
 * @since 16/3/1 上午10:00.
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private RedisDAO rDAO;

    @Autowired
    private UserDAO uDAO;

    @Override
    public void sendMsg(String message, String uId, String tId) {
        rDAO.put(tId, String.format("%s-%s", uId, System.currentTimeMillis()), message);
    }

    @Override
    public Map<String, String> recvMsg(String tId) {
        Map<String, String> uIdMessage = rDAO.get(tId);
        Map<String, String> uInfoMessage = new HashMap<>(uIdMessage.size());
        Map<Integer, UserDO> userMap = processUsers(uDAO.selectUserByIds(processKeys(uIdMessage)));
        for (Map.Entry<String, String> uId : uIdMessage.entrySet()) {
            String suffixId = uId.getKey();
            String name = userMap.get(getRealId(suffixId)).getName();
            uInfoMessage.put(String.format("%s %s 说", name, getSendTime(suffixId)), uId.getValue());
        }

        return uInfoMessage;
    }

    @Override
    public Long getNewMsgCount(String tId) {
        return rDAO.count(tId);
    }

    private Integer getRealId(String key) {
        return Integer.parseInt(key.substring(0, key.indexOf('-')));
    }

    private String getSendTime(String key) {
        String millis = key.substring(key.indexOf('-') + 1);
        SimpleDateFormat format = new SimpleDateFormat("MM月dd号 hh:mm:ss");
        return format.format(new Date(Long.parseLong(millis)));
    }

    private Set<Integer> processKeys(Map<String, String> map) {
        Set<Integer> set = new HashSet<>();
        for (String key : map.keySet()) {
            set.add(getRealId(key));
        }

        return set;
    }

    private Map<Integer, UserDO> processUsers(List<UserDO> users) {
        Map<Integer, UserDO> map = new HashMap<>();
        for (UserDO user : users) {
            map.put(user.getId(), user);
        }
        return map;
    }
}
